﻿using B.S.BasicData.Infrastructure.Implement;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Infrastructure;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using AuthCenter.Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace B.S.BasicData.Write.ExtenSions
{
    public static class ServiceCollectionExtensions
    {

        /// <summary>
        /// 依赖注入扩展类
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection Addservices(this IServiceCollection services)
        {
            //注册EF上下文
            services.AddDbContext<SCDbContext>();
            //注册仓储
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //注册中介者
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //注册Automapper
            services.AddAutoMapper(typeof(Myautomapper));
            services.AddScoped<JwtTools>();
            return services;
        }

        public static IServiceCollection AddDBContextService<SCDbContext>(this IServiceCollection services, string? connectionstring, bool enablesqllog) where SCDbContext : DbContext
        {
            return services.AddDbContext<SCDbContext>(builder =>
            {
                builder.UseSqlServer(connectionstring, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();

                if (enablesqllog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }



            });
        }


        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["JwtSettings:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });

        }




    }
}
